package com.yc.cloud.openai.portal.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.yc.cloud.common.basic.exception.Asserts;
import com.yc.cloud.common.basic.utils.FfmpegUtils;
import com.yc.cloud.common.basic.utils.MyFileUtils;
import com.yc.cloud.common.oss.service.OssFileService;
import com.yc.cloud.common.oss.vo.OssFileVo;
import com.yc.cloud.openai.portal.config.PathManager;
import com.yc.cloud.openai.portal.dto.request.VideoRemoveShareWaterMarkParam;
import com.yc.cloud.openai.portal.dto.request.VideoRemoveWaterMarkParam;
import com.yc.cloud.openai.portal.dto.response.VideoRemoveWaterParseResponse;
import com.yc.cloud.openai.portal.service.VideoHelperService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.file.Paths;

/**
 * 视频助手服务实现类
 */
@Service
@Slf4j
public class VideoHelperServiceImpl implements VideoHelperService {
    private final PathManager pathManager;
    private final OssFileService ossFileService;
    @Value("${custom.parsevideo.url}")
    private String parseVideoUrl;

    public VideoHelperServiceImpl(PathManager pathManager, OssFileService ossFileService) {
        this.pathManager = pathManager;
        this.ossFileService = ossFileService;
    }

    /**
     * 移除视频水印
     *
     * @param param 移除水印参数
     * @return 移除水印后的视频路径
     */
    @Override
    public OssFileVo removeShareWatermark(VideoRemoveShareWaterMarkParam param) {
        // 构建请求URL
        String apiUrl = parseVideoUrl + "/video/share/url/parse?url=" + param.getUrl();
        // 使用hutool发送GET请求
        String result;
        try (var response = HttpUtil.createGet(apiUrl)
                .form("url", param.getUrl()) // 添加url参数
                .execute()) {
            result = response.body();
        }
        log.info("移除水印请求结果:{}", result);
        if (StrUtil.isEmpty(result)) {
            Asserts.fail("解析视频分享链接提取失败");
        }
        if (!JSONUtil.isTypeJSON(result)) {
            Asserts.fail("解析视频分享链接提取失败,错误信息:" + result);
        }
        val videoRemoveWaterParseResponse = JSONUtil.toBean(result, VideoRemoveWaterParseResponse.class);
        if (videoRemoveWaterParseResponse.getCode() != 200) {
            Asserts.fail("解析视频分享链接提取失败,错误信息:" + videoRemoveWaterParseResponse.getMsg());
        }
        val videoUrl = videoRemoveWaterParseResponse.getData().getVideoUrl();
        if (StrUtil.isEmpty(videoUrl)) {
            Asserts.fail("解析视频分享链接提取失败,错误信息:视频链接为空");
        }
        val fileId = ossFileService.generateFileId();
        val fileName = fileId + "." + MyFileUtils.getVideoExtension(videoUrl);
        val downloadFilePath = Paths.get(pathManager.getWaterVideoFolder(), fileName).toString();
        HttpUtil.downloadFile(videoUrl, downloadFilePath);
        val noWaterVideo = ossFileService.saveOssFile(downloadFilePath);
        if (noWaterVideo == null) {
            Asserts.fail("保存视频文件信息失败");
        }
        //这里需要将视频的url设置到返回值中,目前没有把视频下载下来
//        ossFileVo.setUrl(videoUrl);
        return ossFileService.convertVo(noWaterVideo);
    }

    @Override
    @SneakyThrows
    public OssFileVo removeWatermark(VideoRemoveWaterMarkParam param) {
        val watermarkVideoOssFile = ossFileService.getByFileIdFromDb(param.getFileId());
        if (watermarkVideoOssFile == null || !FileUtil.exist(watermarkVideoOssFile.getPath())) {
            Asserts.fail("视频文件不存在");
        }
        val fileId = ossFileService.generateFileId();
        //获取文件名字
        val watermarkVideoPath = watermarkVideoOssFile.getPath();
        if (StrUtil.isEmpty(watermarkVideoPath)) {
            Asserts.fail("视频文件路径为空");
        }
        // val prefixName = FileUtil.getPrefix(watermarkVideoPath);
        //生成新的文件名
        val newFileName = fileId + "." + FileUtil.getSuffix(watermarkVideoOssFile.getPath());
        //生成新的文件路径
        val outputPath = Paths.get(pathManager.getWaterVideoFolder(), newFileName).toString();
        //移除水印
        FfmpegUtils.removeWatermark(watermarkVideoOssFile.getPath(), outputPath, param.getX(), param.getY(), param.getWidth(), param.getHeight());
        if (!FileUtil.exist(outputPath) || FileUtil.size(FileUtil.file(outputPath)) == 0) {
            Asserts.fail("移除水印失败");
        }
        //保存视频文件信息到本地
        val ossFile = ossFileService.buildOssFile(fileId, newFileName, outputPath);
        val saveFlag = ossFileService.save(ossFile);
        if (!saveFlag) {
            Asserts.fail("保存视频文件信息失败");
        }
        //删除原来的水印视频文件
//        FileUtil.del(watermarkVideoPath);
        return ossFileService.convertVo(ossFile);
    }
}


